"""
日志配置
@author:yczha
"""
import os
import sys
import logging
from logging.handlers import TimedRotatingFileHandler
from datetime import datetime

WORK_DIR = os.path.dirname(os.path.dirname(__file__))


def get_logger():
    """配置日志"""
    log_dir = os.path.join(WORK_DIR, 'logs')
    if not os.path.isdir(log_dir):
        os.makedirs(log_dir)

    BASIC_FORMAT = "%(asctime)s\t| %(levelname)s\t| %(filename)s:%(lineno)s - %(message)s"
    DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
    formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT)
    logger = logging.getLogger(__name__)
    # logger.setLevel(logging.INFO)
    levels = ['debug', 'info', 'warning', 'error']
    for level in levels:
        log_filter = logging.Filter()

        def set_filter(level):
            log_filter.filter = lambda record: record.levelno == eval(
                f'logging.{level.upper()}')  # 设置过滤等级
        set_filter(level)
        if level == 'error':
            log_handler = logging.StreamHandler(sys.stderr)
        else:
            log_handler = logging.StreamHandler(sys.stdout)
        log_handler.addFilter(log_filter)
        log_handler.setFormatter(formatter)
        log_path = os.path.join(
            log_dir, f"{datetime.now().strftime('%Y-%m-%d')}_{level}.log")
        file_handler = TimedRotatingFileHandler(
            filename=log_path, when="D", interval=1, backupCount=30, encoding='utf-8')  # 输出到文件的handler
        file_handler.addFilter(log_filter)
        file_handler.setFormatter(formatter)
        logger.addHandler(log_handler)
        logger.addHandler(file_handler)
    return logger


logger = get_logger()


if __name__ == '__main__':
    logger.info('==========test info==============')
    logger.warning('===========test warnning=======')
    logger.error('=========test error==============')
